package com.anche.cywebnew.Controller.systemManager;

import com.alibaba.fastjson.JSONObject;
import com.anche.cywebnew.Pojo.systemManager.SysOrganization;
import com.anche.cywebnew.Service.systemManager.OrganService;
import com.anche.cywebnew.Utils.String.StringUtils;
import com.anche.cywebnew.Utils.Thread.ThreadPoolUtil;
import com.anche.cywebnew.Utils.http.HttpClientResult;
import com.anche.cywebnew.Utils.http.HttpClientUtils;
import com.github.pagehelper.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;

/**
 * @program: cywebnew
 * @description:
 * @author: LCQ
 * @create: 2021-01-20 14:05
 */
@Controller
@RequestMapping("/system/sancnas")
public class ScanNasController {

    private static final Logger logger = LoggerFactory.getLogger(ScanNasController.class);

    @Autowired
    private OrganService organService;

    @RequestMapping("/manager")
    public String toOrganPage() {
        return "/systemManager/scannas";
    }

    @GetMapping(value = "/organListPager")
    @ResponseBody
    public Object organListPager(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit, SysOrganization sysOrganization) {
        Map<String, Object> map = new HashMap<>();
        try {
            Page<SysOrganization> pageInfo = organService.getOrganListPage(page, limit, sysOrganization);
            List<SysOrganization> sysOrganizationList = pageInfo.getResult();
            List<Map<String, Object>> list = new ArrayList<>();
            final CountDownLatch cdl = new CountDownLatch(sysOrganizationList.size() * 2);  // 多线程同步
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for (SysOrganization soz : sysOrganizationList) {
                Map<String, Object> temp = new HashMap<>();
                temp.put("cyqxh",soz.getCyqxh());
                temp.put("cyqmc",soz.getName());
                temp.put("ip",soz.getIp());

                // 扫描Nas硬盘
                ThreadPoolUtil.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String url = "http://IP:PORT/stationserver/station/testNas";
                            if(!StringUtils.isEmpty(soz.getIp())){
                                url = url.replace("IP",soz.getIp());
                            }
                            if(!StringUtils.isEmpty(soz.getPort())){
                                url = url.replace("PORT",soz.getPort());
                            }
                            logger.info("扫描url:"+url);
                            HttpClientResult hcr = HttpClientUtils.doGet(url);
                            if(200 == hcr.getCode()){
                                Map<String,String> result = JSONObject.parseObject(hcr.getContent(),Map.class);
                                if(result != null && "1".equals(result.get("code"))){
                                    temp.put("nasstatus","1");
                                    temp.put("naslocation",result.get("nas_location"));
                                }else{
                                    temp.put("nasstatus","2");
                                    temp.put("naslocation",result.get("nas_location"));
                                }
                            }else{
                                temp.put("nasstatus","2");
                                temp.put("naslocation","");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            logger.error(e.getMessage());
                            temp.put("nasstatus","2");
                            temp.put("naslocation","");
                        }finally {
                            temp.put("nascreatedate",sdf.format(new Date()));
                            cdl.countDown();  // 让latch中的数值减一
                        }
                    }
                });

                // 扫描站点服务
                ThreadPoolUtil.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String url = "http://IP:PORT/stationserver/station/testConn";
                            if(!StringUtils.isEmpty(soz.getIp())){
                                url = url.replace("IP",soz.getIp());
                            }
                            if(!StringUtils.isEmpty(soz.getPort())){
                                url = url.replace("PORT",soz.getPort());
                            }
                            logger.info("扫描url:"+url);
                            HttpClientResult hcr = HttpClientUtils.doGet(url);
                            if(200 == hcr.getCode()){
                                Map<String,String> result = JSONObject.parseObject(hcr.getContent(),Map.class);
                                if(result != null && "1".equals(result.get("code"))){
                                    temp.put("statstatus","1");
                                }else{
                                    temp.put("statstatus","2");
                                }
                            }else{
                                temp.put("statstatus","2");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            logger.error(e.getMessage());
                            temp.put("statstatus","2");
                        }finally {
                            temp.put("statcreatedate",sdf.format(new Date()));
                            cdl.countDown();  // 让latch中的数值减一
                        }
                    }
                });
                list.add(temp);
            }
            cdl.await();   // 主线程阻塞，等待子线程执行完毕
            logger.info("<查询查验机构列表成功>");
            map.put("code", "0");
            map.put("count", pageInfo.getTotal());
            map.put("msg", "查询成功");
            map.put("data", list);
        } catch (Exception e) {
            logger.error("<查询查验机构列表异常:[{}]>", e.getMessage());
            e.printStackTrace();
            map.put("code", "1");
            map.put("msg", e.getMessage());
        }
        return map;
    }

}
